package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.LoginService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.TimerUtil;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.SecurityCodeView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: WithdrawActivity
 * @Description: 提现页面
 * @Author: ljp
 * @CreateDate: 2018/10/9 15:27
 * @Version: 1.0
 */
public class WithdrawActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.rela_1)
    RelativeLayout rela1;
    @BindView(R.id.image_way)
    ImageView imageWay;
    @BindView(R.id.tv_way)
    TextView tvWay;
    @BindView(R.id.tv_account_name)
    TextView tvAccountName;
    @BindView(R.id.linear_way)
    LinearLayout linearWay;
    @BindView(R.id.et_cash_money)
    EditText etCashMoney;
    @BindView(R.id.remaining_sum)
    TextView remainingSum;
    @BindView(R.id.tv_all_cash)
    TextView tvAllCash;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.linear_normal)
    LinearLayout linearNormal;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.linear_red)
    LinearLayout linearRed;
    @BindView(R.id.tv_cash)
    TextView tvCash;
    @BindView(R.id.tv_terms)
    TextView tvTerms;
    private int diamondSum;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String accountId;
    private String account;//支付宝账号
    private String TAG = "WithdrawActivity";
    private TimerUtil mTimer;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_withdraw;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        initView();
    }

    /**
     * @return
     * @method
     * @description 数据实例化
     * @date: 2018/10/9 17:08
     * @author: ljp
     */
    private void initView() {
        diamondSum = getIntent().getIntExtra("diamondSum", 0);
        account = getIntent().getStringExtra("account");
        Log.i(TAG, "initView: --account--"+account);
        tvAccountName.setText(Utils.getName(account));
        //double div = Utils.div(diamondSum, 10, 2);
        int money = diamondSum/10;
        remainingSum.setText("钻石余额" + diamondSum + ",可提现余额" + money);
        tvAllCash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (money >= 50) {
                    etCashMoney.setText(String.valueOf(money));
                    etCashMoney.setSelection(String.valueOf(money).length());
                } else {
                    toast_MakeText(getResources().getString(R.string.low));
                }
            }
        });
        etCashMoney.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
        etCashMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String trim = s.toString().trim();
                if (trim.startsWith("0") && trim.length() == 1) {
                    etCashMoney.setText("");
                    return;
                }
                if (trim.length() < 4 && trim.contains(".")) {
                    String substring = trim.substring(0, trim.length() - 1);
                    etCashMoney.setText(substring);
                    etCashMoney.setSelection(substring.length());
                    return;
                }
                //设置不能连续输入0
                if (trim.startsWith("0")
                        && trim.length() > 1) {
                    if (!trim.substring(1, 2).equals(".")) {
                        etCashMoney.setText(trim.subSequence(0, 1));
                        etCashMoney.setSelection(1);
                        return;
                    }
                }
                //保留小数点后两位
               /* if (trim.contains(".")) {
                    if (trim.length() - 1 - trim.indexOf(".") > 2) {
                        s = trim.subSequence(0,
                                trim.indexOf(".") + 2 + 1);
                        etCashMoney.setText(s);
                        etCashMoney.setSelection(s.length());
                    }
                } else*/ if (trim.length() > 5) {
                    String substring = trim.substring(0, 5);
                    etCashMoney.setText(substring);
                    etCashMoney.setSelection(substring.length());
                }
                if (!TextUtils.isEmpty(trim)) {
                   /* int firstIdex = trim.indexOf(".");
                    int lastIndex = trim.lastIndexOf(".");
                    if (firstIdex == lastIndex && firstIdex != 0) {//已经存在一个小数点且小数点不在第一个位置*/
                        float parse = Float.parseFloat(trim);
                        if (parse < 50) {//判断金额是否大于最低提现金额
                            layoutUnclickable();
                            tvHint.setText("提现金额需≥50元");
                        } else if (parse > (diamondSum/10)) {//判断金额是否大于余额
                            layoutUnclickable();
                            tvHint.setText("金额已超过可提现余额");
                        } else {
                            layoutClickable();
                            tvCash.setClickable(true);
                            tvCash.setBackgroundResource(R.drawable.login_btn);
                        }
                   /* } else {
                        if (trim.length() == 1) {
                            etCashMoney.setText("");
                        } else {
                            etCashMoney.setText(trim.substring(0, trim.length() - 1));
                            etCashMoney.setSelection(trim.length() - 1);
                        }
                    }*/
                } else {
                    layoutClickable();
                    tvCash.setClickable(false);
                    tvCash.setBackgroundResource(R.drawable.login_btn_2);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }


    @OnClick({R.id.linear_back, R.id.linear_way, R.id.tv_cash,R.id.tv_terms})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back://返回
                finish();
                break;
            case R.id.linear_way://选择到账方式
                //showPopuWay(view);
                break;
            case R.id.tv_cash://提现
                //showPopuWay(view);
                showGoldPopu();
                break;
            case R.id.tv_terms://用户提现协议
                Intent intent = new Intent(activity, WebPageActivity.class);
                intent.putExtra("url","file:///android_asset/web/cash.html");
                intent.putExtra("title","用户提现协议");
                startActivity(intent);
                break;
        }
    }
    /**
     * @method
     * @description 提现发送验证码
     * @date: 2018/11/26 17:55
     * @author: ljp
     * @return
     */
    private void showGoldPopu() {
        //获取验证码
        getVaCode();
        View view = View.inflate(context,R.layout.popu_withdraw_layout,null);
        PopUtils.showPopupWindow(activity,view,false);
        ImageView imgeClose = view.findViewById(R.id.image_close);//关闭
        SecurityCodeView scCode = view.findViewById(R.id.sc_code);
        TextView tvPhone = view.findViewById(R.id.tv_phone);//手机号码
        TextView tvCode = view.findViewById(R.id.tv_get_code);//验证码倒计时
        TextView tvSure = view.findViewById(R.id.tv_sure);//确定按钮
        mTimer = new TimerUtil(60, tvCode, this);
        tvPhone.setText("已经发送验证码至"+SPUtils.getEditoString(SPUtils.SP_PHONE));

        scCode.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                String trim = scCode.getEditContent().trim();
                if (trim.length() == 4) {
                    tvSure.setClickable(true);
                    tvSure.setBackgroundResource(R.drawable.login_btn);
                }
            }
            @Override
            public void deleteContent(boolean isDelete) {
                tvSure.setBackgroundResource(R.drawable.login_btn_2);
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = scCode.getEditContent().trim();
                setHttp(trim);
            }
        });
        imgeClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
            }
        });
    }
    /**
     * @return
     * @method
     * @description 获取验证码
     * @date: 2018/9/19 11:30
     * @author: ljp
     */
    private void getVaCode() {
        LoginService.loginGetVCode(SPUtils.getEditoString(SPUtils.SP_PHONE), LoginService.VALIDATE_CODE_TYPE.VALIDATE_CODE_WITHDRAW).subscribe(result -> {
            Log.i(TAG, "getVaCode: ----"+result.toString());
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                mTimer.myStart(0);
                toast_MakeText("验证码发送成功!");
            }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText("验证码发送失败!");
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "getVaCode: -----"+throwable.toString());
        });
    }
    /**
     * @return
     * @method
     * @description 提现
     * @date: 2018/11/29 16:44
     * @author: ljp
     */
    private void setHttp(String code) {
        String rmb = etCashMoney.getText().toString().trim();
        MeInfoService.setWithdraw(mySeleInfo.getId(), SPUtils.getEditoString(SPUtils.SP_TOKEN),
                PhoneUtils.getDeviceInfo(context), account, rmb, String.valueOf(diamondSum),
                MeInfoService.AISLE_TYPE.AISLE_TYPE_2,code).subscribe(result -> {
            Log.i(TAG, "setHttp: ---------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Intent intent = new Intent(activity,AllSuccessActivity.class);
                intent.putExtra("flag","3");
                startActivity(intent);
                finish();
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "setHttp: -------" + throwable.toString());

        });

    }

    /**
     * @return
     * @method
     * @description 选择支付方式popu
     * @date: 2018/10/9 16:36
     * @author: ljp
     */
    private void showPopuWay(View v) {
        View view = View.inflate(context, R.layout.popu_account_way, null);
        PopUtils.showPopupWindow(this, view, false);
        LinearLayout back = view.findViewById(R.id.linear_close);
        LinearLayout linear_z = view.findViewById(R.id.linear_zhifubao);
        LinearLayout linear_w = view.findViewById(R.id.linear_weixin);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
            }
        });
    }

    /**
     * @return
     * @method
     * @description 按钮不可点击状态
     * @date: 2018/10/9 19:33
     * @author: ljp
     */
    private void layoutUnclickable() {
        viewLine.setBackgroundColor(getResources().getColor(R.color.colorFF3B5E));
        linearNormal.setVisibility(View.GONE);
        linearRed.setVisibility(View.VISIBLE);
        tvCash.setClickable(false);
        tvCash.setBackgroundResource(R.drawable.login_btn_2);
    }

    /**
     * @return
     * @method
     * @description 默认状态状态
     * @date: 2018/10/9 19:33
     * @author: ljp
     */
    private void layoutClickable() {
        viewLine.setBackgroundColor(getResources().getColor(R.color.colorEEEEEE));
        linearNormal.setVisibility(View.VISIBLE);
        linearRed.setVisibility(View.GONE);
    }

}
